package tree.迭代bfs;

import po.TreeNode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName N二叉树最大宽度662.java
 * @Description https://leetcode-cn.com/problems/maximum-width-of-binary-tree/
 * @createTime 2021年06月30日 19:24:00
 */
public class N二叉树最大宽度662 {
    public int widthOfBinaryTree(TreeNode root) {
        int max = 0;
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            //计算第一个节点和最后一个节点的值的差+1 就是宽度。
            max = Math.max(max, deque.getLast().val - deque.getFirst().val + 1);
            for (int i = 0; i < size; i++) {
                TreeNode node = deque.remove();
                if (node.left != null) {
                    node.left.val = node.val * 2 + 1;
                    deque.add(node.left);
                }
                if (node.right != null) {
                    node.right.val = node.val * 2 + 2;
                    deque.add(node.right);
                }
            }
        }
        return max;
    }
}
